<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useMessage } from 'naive-ui';
import { fetchGetConfigList, fetchUpdateConfig } from '@/service/api/system/config';
import OssUpload from '@/components/custom/oss-upload.vue';

defineOptions({
  name: 'WxPayConfig'
});

const message = useMessage();

// 微信支付配置表单
interface WxPayConfig {
  appId: string;
  mchId: string;
  mchKey: string;
  keyPathId: string;
  notifyUrl: string;
  enabled: boolean;
}

const wxPayConfig = reactive<WxPayConfig>({
  appId: '',
  mchId: '',
  mchKey: '',
  keyPathId: '',
  notifyUrl: '',
  enabled: false
});

const loading = ref(false);
const saving = ref(false);

// 加载微信支付配置
async function loadWxPayConfig() {
  loading.value = true;
  try {
    // 获取所有配置项
    const { data } = await fetchGetConfigList({
      pageNum: 1,
      pageSize: 100,
      configKey: 'wxpay'
    });

    if (data && data.rows) {
      data.rows.forEach((config: any) => {
        switch (config.configKey) {
          case 'mini_appId':
            wxPayConfig.appId = config.configValue || '';
            break;
          case 'wxpay_mchId':
            wxPayConfig.mchId = config.configValue || '';
            break;
          case 'wxpay_mchKey':
            wxPayConfig.mchKey = config.configValue || '';
            break;
          case 'wxpay_keyPath':
            wxPayConfig.keyPathId = config.configValue || '';
            break;
          case 'wxpay_notify_url':
            wxPayConfig.notifyUrl = config.configValue || '';
            break;
          case 'wxpay_enabled':
            wxPayConfig.enabled = config.configValue === 'true';
            break;
          default:
            // 其他配置项不处理
            break;
        }
      });
    }
  } catch (error) {
    message.error('加载微信支付配置失败');
    // eslint-disable-next-line no-console
    console.error('加载微信支付配置失败:', error);
  } finally {
    loading.value = false;
  }
}

// 保存微信支付配置
async function saveWxPayConfig() {
  saving.value = true;
  try {
    // 获取现有配置项的ID
    const { data } = await fetchGetConfigList({
      pageNum: 1,
      pageSize: 100,
      configKey: 'wxpay'
    });

    const configMap = new Map();
    if (data && data.rows) {
      data.rows.forEach((config: any) => {
        configMap.set(config.configKey, config.configId);
      });
    }

    // 更新各个配置项
    const updatePromises = [];

    // 更新小程序AppID
    if (configMap.has('mini_appId')) {
      updatePromises.push(
        fetchUpdateConfig({
          configId: configMap.get('mini_appId'),
          configKey: 'mini_appId',
          configValue: wxPayConfig.appId,
          configName: '小程序AppID',
          configType: 'N',
          remark: '微信小程序的AppID，用于微信支付'
        })
      );
    }

    // 更新商户号
    if (configMap.has('wxpay_mchId')) {
      updatePromises.push(
        fetchUpdateConfig({
          configId: configMap.get('wxpay_mchId'),
          configKey: 'wxpay_mchId',
          configValue: wxPayConfig.mchId,
          configName: '微信支付商户号',
          configType: 'N',
          remark: '微信支付分配的商户号'
        })
      );
    }

    // 更新商户密钥
    if (configMap.has('wxpay_mchKey')) {
      updatePromises.push(
        fetchUpdateConfig({
          configId: configMap.get('wxpay_mchKey'),
          configKey: 'wxpay_mchKey',
          configValue: wxPayConfig.mchKey,
          configName: '微信支付商户密钥',
          configType: 'N',
          remark: '微信支付商户密钥，用于签名验证'
        })
      );
    }

    // 更新证书路径
    if (configMap.has('wxpay_keyPath')) {
      updatePromises.push(
        fetchUpdateConfig({
          configId: configMap.get('wxpay_keyPath'),
          configKey: 'wxpay_keyPath',
          configValue: wxPayConfig.keyPathId,
          configName: '微信支付证书路径',
          configType: 'N',
          remark: '微信支付证书文件路径，存储在文件系统中'
        })
      );
    }

    // 更新回调地址
    if (configMap.has('wxpay_notify_url')) {
      updatePromises.push(
        fetchUpdateConfig({
          configId: configMap.get('wxpay_notify_url'),
          configKey: 'wxpay_notify_url',
          configValue: wxPayConfig.notifyUrl,
          configName: '微信支付回调地址',
          configType: 'N',
          remark: '微信支付结果通知的回调地址'
        })
      );
    }

    // 更新启用状态
    if (configMap.has('wxpay_enabled')) {
      updatePromises.push(
        fetchUpdateConfig({
          configId: configMap.get('wxpay_enabled'),
          configKey: 'wxpay_enabled',
          configValue: wxPayConfig.enabled ? 'true' : 'false',
          configName: '微信支付开关',
          configType: 'N',
          remark: '是否启用微信支付功能 (true/false)'
        })
      );
    }

    await Promise.all(updatePromises);
    message.success('微信支付配置保存成功');
  } catch (error) {
    message.error('保存微信支付配置失败');
    // eslint-disable-next-line no-console
    console.error('保存微信支付配置失败:', error);
  } finally {
    saving.value = false;
  }
}

// 测试配置
function testConfig() {
  if (!wxPayConfig.appId || !wxPayConfig.mchId || !wxPayConfig.mchKey) {
    message.warning('请先填写完整的微信支付配置信息');
    return;
  }
  message.info('配置测试功能开发中');
}

// 页面加载时获取配置
loadWxPayConfig();
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden">
    <NCard title="微信支付配置" :bordered="false" class="card-wrapper">
      <NSpin :show="loading">
        <NForm :model="wxPayConfig" :show-require-mark="false" label-width="120px" label-placement="left">
          <NGrid :cols="24" :x-gap="18">
            <NGi :span="24">
              <NFormItem label="启用微信支付" path="enabled">
                <NSwitch v-model:value="wxPayConfig.enabled">
                  <template #checked>启用</template>
                  <template #unchecked>禁用</template>
                </NSwitch>
              </NFormItem>
            </NGi>

            <NGi :span="24">
              <NFormItem label="小程序AppID" path="appId" required>
                <NInput v-model:value="wxPayConfig.appId" placeholder="请输入微信小程序AppID" />
              </NFormItem>
            </NGi>

            <NGi :span="24">
              <NFormItem label="商户号" path="mchId" required>
                <NInput v-model:value="wxPayConfig.mchId" placeholder="请输入微信支付商户号" />
              </NFormItem>
            </NGi>

            <NGi :span="24">
              <NFormItem label="商户密钥" path="mchKey" required>
                <NInput
                  v-model:value="wxPayConfig.mchKey"
                  type="password"
                  show-password-on="mousedown"
                  placeholder="请输入微信支付商户密钥"
                />
              </NFormItem>
            </NGi>

            <NGi :span="24">
              <NFormItem label="证书文件" path="keyPathId">
                <OssUpload
                  v-model:value="wxPayConfig.keyPathId"
                  :max="1"
                  :file-size="10"
                  accept=".p12,.pem,.crt,.key"
                  upload-type="file"
                />
              </NFormItem>
            </NGi>

            <NGi :span="24">
              <NFormItem label="回调地址" path="notifyUrl" required>
                <NInput
                  v-model:value="wxPayConfig.notifyUrl"
                  placeholder="https://your-domain.com/api/wxpay/notify"
                />
              </NFormItem>
            </NGi>

            <NGi :span="24">
              <div class="flex gap-12px">
                <NButton type="primary" :loading="saving" @click="saveWxPayConfig">保存配置</NButton>
                <NButton @click="testConfig">测试配置</NButton>
                <NButton @click="loadWxPayConfig">重新加载</NButton>
              </div>
            </NGi>
          </NGrid>
        </NForm>
      </NSpin>
    </NCard>

    <NCard title="配置说明" :bordered="false" class="card-wrapper">
      <NSpace vertical>
        <div>
          <strong>1. 获取商户信息：</strong>
          <p>登录微信商户平台 (pay.weixin.qq.com)，在"账户中心" -> "商户信息"中获取商户号和商户密钥</p>
        </div>
        <div>
          <strong>2. 设置支付授权目录：</strong>
          <p>在微信商户平台的"产品中心" -> "开发配置"中设置支付授权目录和回调地址</p>
        </div>
        <div>
          <strong>3. 下载证书文件：</strong>
          <p>在微信商户平台的"账户中心" -> "API安全"中下载API证书（支持 .p12、.pem、.crt、.key 格式，最大10MB）</p>
        </div>
        <div>
          <strong>4. 回调地址说明：</strong>
          <p>回调地址应该是您的后端服务地址，用于接收微信支付结果通知，格式为：https://your-domain.com/api/wxpay/notify</p>
        </div>
        <div>
          <strong>5. 安全提醒：</strong>
          <p class="text-red-500">商户密钥和证书文件是敏感信息，请妥善保管，不要泄露给第三方</p>
        </div>
      </NSpace>
    </NCard>
  </div>
</template>

<style scoped></style>